<?php

namespace App\Http\Controllers\Marketing;


use App\Events\Event;
use App\Events\StudentEvent;
use App\Model\Foundation\Student;
use App\Model\Marketing\Contact;
use App\Model\Marketing\Device;
use App\Model\Marketing\Lead;
use App\Model\Marketing\Post;
use Illuminate\Http\Request;
use App\Model\System\Token;
use Laravel\Lumen\Routing\Controller as BaseController;

use App\Http\Controllers\MessagePacket;


class LeadController extends BaseController
{
    use MessagePacket;


    /**
     * 获取单一
     * @param $id
     * @return packetMessage
     */
    function get($id)
    {
        $id = intval($id);
        $obj = Lead::find($id);
        $device = Device::where('clientid',$id)->first();
        if(!empty($device)){
            $device->deviceinfo = json_decode($device->deviceinfo);
        }
        $obj->device = $device;
        if(empty($obj)){
            return $this->fail($obj, '数据不存在');
        }
        return $this->success($obj);
    }

    /**
     * 批量查询
     * @param Request $request
     * @return packetMessage
     */
    function gets(Request $request)
    {
        $query =  Lead::wherenotNull('id');
        # 条件
        if($request->has('status')){
            $status = $request->get('status');
            $query->where('status', $status);
        }

        $query->where(function ($query) use ($request){
            if($request->has('postid')){
                $postid = $request->get('postid');
                $query->orwhere('postid', $postid);
            }
            if($request->has('number')){
                $number = $request->get('number');
                $query->orwhere('number', 'like', "%$number%");
            }
            if($request->has('name')){
                $name = $request->get('name');
                $query->orwhere('name', 'like', "%$name%");
            }
        });

        $query->orderBy('id', 'desc');

        # 需要／不需要 分页
        if($request->has('page')){
            $limit = 30;
            if ($request->has('perPage')) {
                $limit = $request->get('perPage');
            }

            $infos = $query->paginate($limit);
            $leads = $infos->items();
        }else{
            $leads = $query->get();
        }

        # 关联
        foreach ($leads as $key => $lead) {
            $id = $lead->id;
            $device = Device::where('clientid',$id)->first();
            if(!empty($device)){
                $device->deviceinfo = json_decode($device->deviceinfo,JSON_UNESCAPED_UNICODE);
            }
            $lead->device = $device;
            $leads[$key] = $lead;
        }

        # 需要／不需要 分页
        if($request->has('page')){
            $infos = $infos->toArray();
            unset($infos['data']);
            $data['list'] = $leads;
            $data['pager'] = $infos;
        }else{
            $data = $leads;
        }

        if(empty($data)){
            return $this->fail($data, '数据不存在');
        }
        return $this->success($data);
    }


    /**
     * 添加一个
     * @param Request $request
     * @return packetMessage
     */
    function  create(Request $request)
    {

        try{
            $obj = new Lead($request->all());
            $post = Post::find($request->postid);
            $obj->posttitle = $post->title;
            $obj->save();
            return $this->success($obj);
        }catch (\Exception $e){
            if($obj){
                $this->delete($obj->id);
            }
            return $this->fail(false,'添加失败:'.$e->getMessage());
        }
    }


    /**
     * 更新某个
     * @param Request $request
     * @return packetMessage
     */
    function  update($id, Request $request)
    {
        try{
            $obj = Lead::find($id);
            if($request->has('ClassInNo')){
                $student = new Student();
                $student->ClassInNo = $request->get('ClassInNo');
                $student->name = $request->get('name');
                $password = null;
                if($request->has('password')){
                    $password = $request->get('password');
                }
                $this->dispatchStudentEvent($student,StudentEvent::CREATE,$password);
            }
            $fields = $request->all();
            $obj->update($request->all());
            $obj->updated_by = Token::user()->userid;

            if($obj->save()){
                return $this->success($obj);
            }else{
                return $this->fail(false,'保存失败');
            }
        }catch (\Exception $e){
            return $this->fail(false,"保存失败：".$e->getMessage());
        }

    }

    /**
     * 禁用
     * @param $id
     * @return packetMessage
     */
    function  disable($id)
    {
        $obj = Lead::find($id);
        $obj->status = Lead::DISABLE;
        if($obj->save()){
            return $this->success(true);
        }else{
            return $this->fail(false, '失败');
        }
    }

    /**
     * 启用
     * @param $id
     * @return packetMessage
     */
    function  enable($id)
    {
        $obj = Lead::find($id);
        $obj->status = Lead::ENABLE;
        if($obj->save()){
            return $this->success(true);
        }else{
            return $this->fail(false, '失败');
        }
    }

    /**
     * 删除潜客记录
     * @param $id
     * @return packetMessage
     */
    function  delete($id)
    {
        try{
            Device::where('clientid', $id)->delete();
            Contact::where('clientid', $id)->delete();
            Lead::destroy($id);
            return $this->success(true);
        }catch (\Exception $e){
            return $this->fail(false,'删除失败:'.$e->getMessage());
        }
    }

    /**
     * 添加一个沟通记录
     * @param Request $request
     * @return packetMessage
     */
    function  createContact(Request $request)
    {
        if(!$request->has('clientid')){
            return $this->fail(false,'参数不全');
        }
        $obj = new Contact($request->all());
        if($obj->save()){
            return $this->success($obj);
        }
        return $this->fail(false,'创建失败');
    }

    /**
     * 删除一个沟通记录
     * @param Request $request
     * @return packetMessage
     */
    function  deleteContact($id)
    {
        if( Contact::destroy($id)){
            return $this->success(true);
        }
        return $this->fail(false,'删除失败');
    }

    /**
     * 获取一个沟通记录
     * @param Request $request
     * @return packetMessage
     */
    function  getContact($id)
    {
        $obj = Contact::find($id);
        if(empty($obj)){
            return $this->fail($obj, '数据不存在');
        }
        return $this->success($obj);
    }

    /**
     * 获取多条沟通记录
     * @param Request $request
     * @return packetMessage
     */
    function  getContacts($id)
    {
        $data = Contact::where('clientid',$id)->get();
        if(empty($data)){
            return $this->fail($data, '数据不存在');
        }
        return $this->success($data);
    }

    /**
     * 学生抛出事件
     * @param Student $student
     * @param $action
     * @return mixed
     * @throws \Exception
     */
    protected function dispatchStudentEvent(Student $student, $action,$password = null)
    {
        try{
            $event = new StudentEvent($student, $action,$password);
            event($event);
        }catch (\Exception $e){
            throw $e;
            return $e->getMessage();
        }
    }
}
